﻿Public Class frmSelectXmlFile
    Private ImportPath As String = Application.StartupPath & "\Import\"
    Private counter As New ArrayList


    Private Sub frmSelectXmlFile_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim foundFilesTMP = My.Computer.FileSystem.GetFiles(ImportPath)
        Dim foundFiles() As String = foundFilesTMP.ToArray()
        Dim file As String
        Dim i As Integer
        System.Array.Sort(Of String)(foundFiles)
        For Each file In foundFiles
            i = dgView.Rows.Add()
            dgView.Item(1, i).Value = IO.File.GetLastWriteTime(file).ToShortDateString()
            file = IO.Path.GetFileName(file)
            dgView.Item(2, i).Value = file
        Next
    End Sub


    Private Sub dgView_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles dgView.CellBeginEdit
        If e.ColumnIndex <> 0 Then
            e.Cancel = True
        End If
    End Sub


    Private Sub btnOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOk.Click
        Dim files As New ArrayList
        Dim i As Integer, j As Integer, n As Integer, m As Integer
        'Собираем массив выбранных xml файлов
        For i = 0 To dgView.Rows.Count - 1
            If dgView.Item(0, i).Value = True Then
                files.Add(dgView.Item(2, i).Value)
            End If
        Next

        If files.Count = 0 Then
            MsgBox("Сначала выберите файлы импорта", MsgBoxStyle.Exclamation)
            Exit Sub
        End If

        'Собираем из xml файлов один excel файл
        Dim part() As Object
        Dim adverts As ArrayList
        Dim adv_name As String
        Dim parse As Object
        Dim tpl_main As String = TplLoad("excel.tpl", System.Text.Encoding.UTF8)
        Dim tpl_title As String = TplLoad("excel.title.tpl", System.Text.Encoding.UTF8)
        Dim tpl_row As String = TplLoad("excel.row.tpl", System.Text.Encoding.UTF8)
        Dim lines As String, rows As String
        Dim file As String
        Dim xmlDoc As New MSXML2.DOMDocument60
        Dim xmlNodeList As MSXML2.IXMLDOMNodeList
        Dim xmlNode As MSXML2.IXMLDOMNode
        Dim tmpS As String
        Dim phones() As Object, street As String, nomer As String, text As String

        counter.Clear()
        ReDim part(files.Count - 1)
        For i = 0 To files.Count - 1
            file = files(i)
            adverts = New ArrayList
            'Читаем XML файл
            Try
                xmlDoc.async = False
                xmlDoc.validateOnParse = False
                xmlDoc.load(ImportPath & file)
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Exclamation)
                Exit Sub
            End Try

            'Если это первый в списке файл, то получаем значение adv_name
            'If i = 0 Then
            xmlNode = xmlDoc.getElementsByTagName("Adverts")(0)
            adv_name = getNodeText(xmlNode, "adv_name")
            'End If

            xmlNodeList = xmlDoc.getElementsByTagName("Advert")
            If xmlNodeList.length > 0 Then
                For Each xmlNode In xmlNodeList
                    phones = Split(getNodeText(xmlNode, "phone"), "|")
                    For j = 0 To UBound(phones)
                        'Проверка на риэлторов
                        If DBEstate_isEstate(phones(j), True) = True Then
                            GoTo next_node
                        End If
                        'Добавляем телефон в массив существующих телефонов
                        counter.Add(phones(j))
                    Next j

                    street = getNodeText(xmlNode, "street")
                    nomer = getNodeText(xmlNode, "nomer")
                    text = getNodeText(xmlNode, "text")
                    street = IIf(nomer <> "", street & ", " & nomer, street) & ", "
                    text = Trim(street & text)
                    adverts.Add({text, phones})
next_node:
                Next
            End If

            part(i) = {adv_name, adverts}
        Next

        Dim col1 As String, col2 As String, col3 As String
        lines = ""
        For i = 0 To files.Count - 1
            file = files(i)
            'Если это первый в списке файл, то получаем значение adv_name
            If i = 0 Then adv_name = part(i)(0)

            'Собираем все объявления одного файла
            adverts = part(i)(1)
            rows = ""
            For j = 0 To adverts.Count - 1
                parse = Nothing
                'Текст
                TplAddParse(parse, "text", adverts(j)(0))

                'Телефоны
                phones = adverts(j)(1)
                TplAddParse(parse, "phones", Join(phones, "&#10;"))

                'Собираем количества
                col1 = "" : col2 = "" : col3 = ""
                For n = 0 To phones.Length - 1
                    m = phone_counter(phones(n))
                    'Собираем количество
                    col1 &= IIf(m = 1, m, "<B>" & m & "</B>")
                    If n < (phones.Count - 1) Then col1 &= "&#10;"

                    'Собираем общее количество для текущего сайта
                    col2 &= DBCounter_Get(phones(n), part(i)(0))
                    If n < (phones.Count - 1) Then col2 &= "&#10;"

                    'Собираем общее количество для всех сайтов
                    col3 &= DBCounter_Get(phones(n), "all")
                    If n < (phones.Count - 1) Then col3 &= "&#10;"
                Next n
                TplAddParse(parse, "count", col1)
                TplAddParse(parse, "counter_cur", col2)
                TplAddParse(parse, "counter_all", col3)

                'Парсим объект
                rows &= TplParcer(tpl_row, parse)
            Next j
            'Собираем один файл импорта
            parse = Nothing
            TplAddParse(parse, "title", file)
            TplAddParse(parse, "rows", rows)
            lines &= TplParcer(tpl_title, parse)
        Next i

        'Собираем Excel файл
        parse = Nothing
        TplAddParse(parse, "lines", lines)
        lines = TplParcer(tpl_main, parse)

        'Записываем все в файл
        Try
            Dim SaveFileDialog As New SaveFileDialog
            With SaveFileDialog
                .Title = "Сохранить Excel файл"
                .Filter = "Файл Excel|*.xls"
                .InitialDirectory = ImportPath & "Excel\"
                .FileName = Format(Date.Now, "yyyy.MM.dd_") & adv_name & ".xls"
                If .ShowDialog() <> DialogResult.OK Then Exit Sub
                IO.File.WriteAllText(.FileName, lines, System.Text.Encoding.UTF8)
                file = IO.Path.GetFileName(.FileName)
                If vbYes = MsgBox("Файл " & file & " успешно сохранен" & vbCrLf & "Запустить созданный файл?", MsgBoxStyle.Question + MsgBoxStyle.YesNo) Then
                    Process.Start(.FileName)
                End If
            End With
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub


    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub



    Private Function getNodeText(ByRef xmlNode As MSXML2.IXMLDOMNode, ByVal tag As String) As String
        If IsNothing(xmlNode) Then Return ""
        Dim myNode As MSXML2.IXMLDOMNode = xmlNode.selectSingleNode(tag)
        Return IIf(Not IsNothing(myNode), Trim(myNode.text), "")
    End Function


    Private Function phone_counter(ByVal phone As Object) As Integer
        phone_counter = 0
        For i As Integer = 0 To counter.Count - 1
            If counter(i) = phone Then phone_counter += 1
        Next
    End Function
End Class